import {ScrollView, Text, ToastAndroid, TouchableOpacity, View} from "react-native";
import React, {useCallback, useState} from "react";
import {ScreenHeader} from "./components/ScreenHeader.tsx";
import ProcessTimeline from "../../components/ProcessTimeline.tsx";
import {ApprovalNodeInfo, ProcessInstanceApi} from "../../api/process.ts";
import Icon from "react-native-vector-icons/Ionicons";
import {Reason, ReasonType} from "../../components/Reason.tsx";
import {HeadForm} from "./components/HeadForm.tsx";
import {MainForm} from "./components/MainForm.tsx";
import {getSealInfo} from "../../api/seal.ts";
import {useFocusEffect} from "@react-navigation/native";
import {useAuthStore} from "../../store/authStore.ts";

export function MySealDetail(item: any) {
    const [processNodes, setProcessNodes] = useState<ApprovalNodeInfo[]>([])
    const [isCancelling, setIsCancelling] = useState<boolean>(false)
    const userInfo = useAuthStore((state) => state.userInfo);
    const [status, setStatus] = useState<number>()
    const [canUpdate, setCanUpdate] = useState<boolean>(false);
    const [sealInfo, setSealInfo] = useState<any>(item.route.params.item);

    useFocusEffect(
        useCallback(() => {
            getSealInfo({id: sealInfo.id}).then(res => {
                setSealInfo(res.data);
            });
            ProcessInstanceApi.getApprovalDetail({
                processInstanceId: sealInfo.processInstanceId
            }).then(response => {
                const resData = response.data as any
                if (response?.code === 0 && resData?.activityNodes) {
                    const found = resData.activityNodes.find((node: any) => node.endTime === null);
                    if (found) {
                        console.log(found.id);
                        if (found.id === "First" || found.id === "applicantRevise")
                            setCanUpdate(true);
                    }
                    setProcessNodes(resData.activityNodes)
                    setStatus(resData.status)
                } else {
                    setProcessNodes([])
                }
            }).catch(error => {
                console.error('获取流程信息失败:', error)
                setProcessNodes([])
            })
        }, [sealInfo.id])
    );


    return (
        <View style={{backgroundColor: '#f7f7f7', flex: 1}}>
            <ScreenHeader
                navigation={item.navigation}
                title="用印详情"
                rightText="          "
            />
            {/*这里三个核心组件可以复用*/}
            <ScrollView contentContainerStyle={{paddingBottom: 80}}>
                <HeadForm nickname={userInfo.nickname} sealNumber={sealInfo.sealNumber} status={status}/>
                <MainForm sealInfo={sealInfo} processNodes={processNodes}/>
                <ProcessTimeline activityNodes={processNodes}/>
            </ScrollView>

            <View>
                {(status === 1 || canUpdate) && (
                    <View
                        style={{
                            position: 'absolute',
                            bottom: 0,
                            left: 0,
                            right: 0,
                            backgroundColor: '#fff',
                            borderTopColor: '#eee',
                            flexDirection: 'row',
                        }}
                    >
                        {status === 1 && (
                            <TouchableOpacity
                                style={{
                                    flex: 1,
                                    alignItems: 'center',
                                    paddingVertical: 10,
                                }}
                                onPress={async () => {
                                    setIsCancelling(true);
                                }}
                            >
                                <Icon name={"return-up-back-outline"} size={24} color="#000" />
                                <Text style={{ marginTop: 4 }}>取消申请</Text>
                            </TouchableOpacity>
                        )}

                        {canUpdate && (
                            <TouchableOpacity
                                style={{
                                    flex: 1,
                                    alignItems: 'center',
                                    paddingVertical: 10,
                                }}
                                onPress={async () => {
                                    item.navigation.navigate('CreateSealScreen',{
                                        type: "update",
                                        info: sealInfo
                                    });
                                }}
                            >
                                <Icon name={"create-outline"} size={24} color="#000" />
                                <Text style={{ marginTop: 4 }}>修改申请材料</Text>
                            </TouchableOpacity>
                        )}
                    </View>
                )}
            </View>
            <Reason
                type={ReasonType.CANCEL}
                visible={isCancelling}
                onClose={() => setIsCancelling(false)}
                onSubmit={async (reason) => {
                    console.log('取消理由:', reason);
                    const res = await ProcessInstanceApi.cancelProcessInstanceByStartUser(sealInfo.processInstanceId, reason);
                    if (res.code === 0) {
                        ToastAndroid.show('取消成功', ToastAndroid.SHORT);
                    }
                    setIsCancelling(false);
                }}/>
        </View>
    )
}